﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace Common.Web
{
    /// <summary>
    /// 使用httpclient诊断日志
    /// </summary>
    public static class StartupConfigureExtensionFunctions
    {
        /// <summary>
        /// 使用httpclient诊断日志
        /// </summary>
        /// <param name="services"></param>
        public static void AddHttpClientDiagnostic(this IServiceCollection services)
        {
            DiagnosticListener.AllListeners.Subscribe(new HttpClientDiagnosticObserver());
        }
        /// <summary>
        /// 配置model无效时的响应参数
        /// </summary>
        /// <param name="services"></param>
        public static void ConfigureInvalidModelState(this IServiceCollection services)
        {
            services.Configure<ApiBehaviorOptions>(behavior =>
            {
                behavior.InvalidModelStateResponseFactory = actionContext =>
                {
                    var errorList = actionContext.ModelState.Select(e => new
                    {
                        Field = e.Key,
                        ErrorMessage = e.Value.Errors?.FirstOrDefault()?.ErrorMessage
                    }).ToList();
                    errorList.RemoveAll(s => s == null || string.IsNullOrEmpty(s.ErrorMessage));
                    var result = new FuncResult
                    {
                        Code = "0400",
                        Message = string.Join(";", errorList.Select(e => e.ErrorMessage.Replace("$FIELD$", e.Field)).Distinct())
                    };
                    actionContext.HttpContext.Features.Set(new HttpStatusCodeWrapperFeature(System.Net.HttpStatusCode.BadRequest));
                    var objectResult = new ObjectResult(result);
                    objectResult.StatusCode = StatusCodes.Status200OK;
                    return objectResult;
                };
            });
        }
        /// <summary>
        /// 配置model无效时的响应参数
        /// </summary>
        /// <param name="services"></param>
        /// <param name="useRestful">http状态码跟随code</param>
        public static void ConfigureInvalidModelState(this IServiceCollection services, bool useRestful)
        {
            services.Configure<ApiBehaviorOptions>(behavior =>
            {
                behavior.InvalidModelStateResponseFactory = actionContext =>
                {
                    var errorList = actionContext.ModelState.Select(e => new
                    {
                        Field = e.Key,
                        ErrorMessage = e.Value.Errors?.FirstOrDefault()?.ErrorMessage
                    }).ToList();
                    errorList.RemoveAll(s => s == null || string.IsNullOrEmpty(s.ErrorMessage));
                    var result = new FuncResult
                    {
                        Code = "0400",
                        Message = string.Join(";", errorList.Select(e => e.ErrorMessage.Replace("$FIELD$", e.Field)).Distinct())
                    };
                    actionContext.HttpContext.Features.Set(new HttpStatusCodeWrapperFeature(System.Net.HttpStatusCode.BadRequest));
                    var objectResult = new ObjectResult(result);
                    objectResult.StatusCode = useRestful ? StatusCodes.Status400BadRequest : StatusCodes.Status200OK;
                    return objectResult;
                };
            });
        }
        /// <summary>
        /// 模型绑定消息提供者
        /// </summary>
        /// <param name="webapi"></param>
        public static void ModelBindingMessageProviderSetup(this MvcOptions webapi)
        {
            webapi.ModelBindingMessageProvider.SetNonPropertyUnknownValueIsInvalidAccessor(() => "$FIELD$输入的格式不正确");
            webapi.ModelBindingMessageProvider.SetValueIsInvalidAccessor(value => $"'{value}'输入的格式不正确");
        }
    }
}
